package com.cqcj.login.web;

import com.cqcj.login.pojo.User;
import com.cqcj.login.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;


@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户名与密码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        LoginService loginService = new LoginService();
        User user = loginService.select(username,password);
        if(user != null ){
            if("1".equals(remember)){
                //存在用户,保存cookie
                String key = URLEncoder.encode(username, "UTF-8");//对中文进行URL编码
                String value = URLEncoder.encode(password, "UTF-8");//对中文进行URL编码
                Cookie cookie = new Cookie("username",key);
                Cookie cookie1 = new Cookie("password",value);
                cookie.setMaxAge(60*60*24*7);
                cookie1.setMaxAge(60*60*24*7);
                response.addCookie(cookie);
                response.addCookie(cookie1);
            }
            //保存session
            //1.获取session对象
            HttpSession session = request.getSession();
            //2.设置session值
            session.setAttribute("user",user);
            //重定向到登录成功页面
            //获取项目名称
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/selectBrandAllServlet");
        }else {//不存在用户,弹出警告：用户名或密码不对
            request.setAttribute("error_Msg","用户名或密码不正确");
            request.getRequestDispatcher("/login.jsp").forward(request,response);//转发
        }
    }
}
